//
//  DDExchangeTokenMaskACK.m
//  MyClouds
//
//  Created by sarah doo on 13-8-11.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDExchangeTokenMaskACK.h"

@implementation DDExchangeTokenMaskACK

- (id)initWithData:(NSData *)data {
//    self = [super init];
//    if (self) {
//        self.entity = [[NSMutableData alloc]init];
//        [entity appendData:data];
//    }
    //[self setCmd:CloudCmd_ExchangeTokenMask];
    self = [super initWithData:data];
    return self;
}
- (id)initWithTokenMask:(NSString*)tokenStr{
    self = [super init];
    
    if(self) {
        [self setCmd:CloudCmd_ExchangeTokenMaskAck];
        int cmdLength = HEADER_LENGTH + TOKEN_MASK_LENGTH * 2;
        [self setLength:cmdLength];
        tokenStr = [self generateRandomTokenMask];
        NSData *localData = [tokenStr dataUsingEncoding:NSUnicodeStringEncoding];
        NSRange range;
        range.location = 2;
        range.length = [localData length] - 2;
        localData = [localData subdataWithRange:range];
        [self setToken:localData];
        int crc = [self crcs:entity withLength:[entity length]];
        [self setCrc:crc];
    }
    return self;

}
- (void) setToken:(NSData *)_token
{
    //token = [self sortData:_token];
    
    NSRange range;
    
    range.location = 20;
    range.length = 64 * 2;
    //Byte* entityBytes = (Byte*)[_token bytes];
    [entity replaceBytesInRange:range withBytes:[_token bytes]];
//    entityBytes = (Byte*)[entity bytes];
}

-(NSString*) getTokenMask{
    Byte bytes[] = {255,254};
    bytes[0] = 255;
    bytes[1] = 254;
    NSMutableData *headData = [[NSMutableData alloc]initWithBytes:bytes length:2];
    NSRange range;
    range.location = HEADER_LENGTH;
    range.length = TOKEN_MASK_LENGTH * 2;
    NSData* tokenData = [entity subdataWithRange:range];
   
    [headData appendData:tokenData];
     NSLog(@"after string---------------------%@",tokenData);
    NSString *token = [[NSString alloc]initWithData:headData encoding:NSUnicodeStringEncoding];
    [headData release];
    return token;
}

- (NSString *)generateRandomTokenMask {
    srand(1000);
    NSMutableString *str = [NSMutableString stringWithCapacity:TOKEN_MASK_LENGTH];
    for (int i = 0; i < 63; i++) {
        int x = (rand() % 26) + 'A';
        char y = x;
        [str appendFormat:@"%c",y];
    }
    [str appendString:@"\0"];
    NSString *result = [[str copy]autorelease];
    
    //
    return result ;
}
//接受tockenMask并拼接并加密

@end
